package ualrcdg.server;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Timestamp;
import java.util.HashMap;

import ualrcdg.shared.requests.UpdateProgressRequest;

/**
 * Logs a unit of Player progress and associates that progress with the Player and the Game the Player was playing so that it may be retrieved and utilized later if necessary.
 */
public class ProgressLogger
{
	private final Path logPath;
	private final HashMap< String, HashMap< String, File > > gameLogs; 
	
	/**
	 * Primary constructor
	 * 
	 * @param rootFolder the name of the folder (relative to the current working directory) that contains all files and folders necessary for the CDG Server application
	 * @param logFolder the name of the folder (relative to the rootFolder) that contains any existing (and will contain any newly created) game logs
	 * @throws IOException If the logging directory cannot be created
	 */
	//LATER Add rootPath argument to constructor so that proper directory can be reached
	public ProgressLogger( String rootFolder, String logFolder ) throws IOException
	{
		System.out.println( "ProgressLogger(" + rootFolder + ", " + logFolder + ")" );
		this.logPath = FileSystems.getDefault( ).getPath( rootFolder, logFolder );
		Files.createDirectories( logPath );
		this.gameLogs = new HashMap< String, HashMap<String,File> >( );
	}
	
	/**
	 * Attempts to log a unit of player progress
	 * 
	 * @param request an UpdateProgressRequest object containing the parameters of the logging request
	 * @return true if the update could be logged, false otherwise
	 */
	//LATER Decide on logProgress vs updateProgress naming convention; rename non-conventional classes and methods 
	public boolean logProgress( UpdateProgressRequest request )
	{
		HashMap< String, File > gameLog = gameLogs.get( request.gameId );
		
		if( gameLog == null )
		{
			gameLog = new HashMap< String, File >( );
			gameLogs.put( request.gameId, gameLog );
		}
		
		File playerLog = gameLog.get( request.username );
		
		if( playerLog == null )
		{
			playerLog = logPath.resolve( request.gameId + " - " + request.username + " - log.txt" ).toFile( );
		}
		
		try
		{
			PrintWriter log = new PrintWriter( new FileOutputStream( playerLog, true ) );
			log.println( ( new Timestamp( System.currentTimeMillis( ) ) ).toString( ) + ": " + request.completedTask );
			log.close( );
		}
		catch( FileNotFoundException e )
		{
			System.out.println( "ProgressLogger unable to write to file: " + playerLog.getAbsolutePath( ) );
			return false;
		}
		
		return true;
	}
}
